package com.eduction.controller;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eduction.common.utils.ExcelDownUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eduction.bean.SessionUser;
import com.eduction.common.ReturnCode;
import com.eduction.common.dbutil.page.Page;
import com.eduction.modules.system.entity.SchoolContacts;
import com.eduction.resource.BaseController;
import com.eduction.service.SchoolContactService;

@Controller
@RequestMapping("/contact")
public class SchoolContactController extends BaseController{

	private static final Log logger = LogFactory.getLog(SchoolContactController.class);
	
	@Autowired
	private SchoolContactService schoolContactService;
	
	/**
	 * 查询联系人
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/querySchoolContacts" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> querySchoolContacts(HttpServletRequest request,@RequestBody Map<String ,String> map) {
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		String schoolId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
		String type = map.get("type");
		if(type == null){
			return toResponse(null, ReturnCode.FAIL, "参数为空!");
		}
		try {
//			List<SchoolContacts> list = schoolContactService.querySchoolContacts(type);
			List<SchoolContacts> list = schoolContactService.querySchoolContactsBySchoolIdAndType(schoolId,type);
			if(list == null){
				return toResponse(null, ReturnCode.SUCCESS, "暂无数据!");
			}
			return toResponse(list, ReturnCode.SUCCESS, "查询成功!");
		} catch (SQLException e) {
			logger.error(e);
			return toResponse(null, ReturnCode.FAIL, "查询失败!");
		}
	}
	
	/**
	 * 保存联系人
	 */
	@RequestMapping(value = "/saveSchoolContacts" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> saveSchoolContacts(HttpServletRequest request,@RequestBody Map<String ,String> map) {
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		String schoolId=(String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
		if(schoolId ==null)
			return toResponse(null, ReturnCode.FAIL, "未登录!");
		String createTime =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String name = map.get("name");
		String type = map.get("type");
		String mobilePhone = map.get("mobilePhone");
		String telephone = map.get("telephone");
		String email = map.get("email");
		String address = map.get("address");
		String postcode = map.get("postcode");
		String remark = map.get("remark");
		if(name==null || StringUtils.isBlank(name))
			return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"姓名不能为空");
		if(type==null || StringUtils.isBlank(type))
			return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"职务不能为空");
		if(mobilePhone==null || StringUtils.isBlank(mobilePhone))
			return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"手机号码不能为空");
		if(telephone==null || StringUtils.isBlank(telephone))
			return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"办公电话不能为空");
		if(email==null || StringUtils.isBlank(email))
			return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"邮箱不能为空");
		if(address==null || StringUtils.isBlank(address))
			return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"地址不能为空");
		if(postcode==null || StringUtils.isBlank(postcode))
			return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"邮编不能为空");
		SchoolContacts sc = new SchoolContacts();
		sc.setS_address(address);
		sc.setS_create_time(createTime);
		sc.setS_email(email);
		sc.setS_mobile_phone(mobilePhone);
		sc.setS_name(name);
		sc.setS_postcode(postcode);
		sc.setS_remark(remark);
		sc.setS_school_id(schoolId);
		sc.setS_telephone(telephone);
		sc.setS_type(type);
		schoolContactService.saveSchoolContact(sc);
		return toResponse(sc, ReturnCode.SUCCESS, "添加成功!");
	}
	
	/**
	 * 删除联系人
	 */
	@RequestMapping(value = "/deleteSchoolContacts" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> deleteSchoolContacts(HttpServletRequest request,@RequestBody Map<String ,String> map) {
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		String schoolId=(String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
		if(schoolId ==null)
			return toResponse(null, ReturnCode.FAIL, "未登录!");
		String pid = map.get("pid");
		if(pid == null || StringUtils.isBlank(pid))
			return toResponse(null, ReturnCode.FAIL, "请选择一个对象!");
		schoolContactService.deleteSchoolContact(pid);
		return toResponse(null, ReturnCode.SUCCESS, "删除成功!");
	}
	
	/**
	 * 修改联系人信息
	 */
	@RequestMapping(value = "/updateSchoolContacts" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> updateSchoolContacts(HttpServletRequest request,@RequestBody Map<String ,String> map) {
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		String schoolId=(String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
		if(schoolId ==null)
			return toResponse(null, ReturnCode.FAIL, "未登录!");
		String pid = map.get("pid");
		if(pid == null || StringUtils.isBlank(pid))
			return toResponse(null, ReturnCode.FAIL, "请选择一个对象!");
		String name = map.get("name");
		String type = map.get("type");
		String mobilePhone = map.get("mobilePhone");
		String telephone = map.get("telephone");
		String email = map.get("email");
		String address = map.get("address");
		String postcode = map.get("postcode");
		String remark = map.get("remark");
		try {
			SchoolContacts sc = schoolContactService.querySchoolContactsByPid(pid);
			if(sc == null)
				return toResponse(null, ReturnCode.FAIL, "联系人不存在!");
			if(name!=null && StringUtils.isNotBlank(name))
				sc.setS_name(name);
			if(type!=null && StringUtils.isNotBlank(type))
				sc.setS_type(type);
			if(mobilePhone!=null && StringUtils.isNotBlank(mobilePhone))
				sc.setS_mobile_phone(mobilePhone);
			if(telephone!=null && StringUtils.isNotBlank(telephone))
				sc.setS_telephone(telephone);
			if(email!=null && StringUtils.isNotBlank(email))
				sc.setS_email(email);
			if(address!=null && StringUtils.isNotBlank(address))
				sc.setS_address(address);
			if(postcode!=null && StringUtils.isNotBlank(postcode))
				sc.setS_postcode(postcode);
			if(remark!=null && StringUtils.isNotBlank(remark))
				sc.setS_remark(remark);
			schoolContactService.saveSchoolContact(sc);
			return toResponse(sc, ReturnCode.SUCCESS, "修改成功!");
		} catch (SQLException e) {
			logger.error(e);
			return toResponse(null, ReturnCode.FAIL, "修改失败!");
		} 
	 }
	
	/**********************************************管理员页面**********************************************************************/
	
	/**
	 * 分页查询联系人
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/querySchoolContactsByPage" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> querySchoolContactsByPage(HttpServletRequest request,@RequestBody Map<String ,String> map) {
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		if(map.get("pageNumber") == null || map.get("pageSize") == null || StringUtils.isBlank(map.get("pageNumber")) || StringUtils.isBlank(map.get("pageSize"))){
			return	toResponse(null, ReturnCode.FAIL, "参数不能为空!");
		}
		if(map.get("contentName")==null){
			map.put("contentName","");

		}
		if(map.get("schoolName")==null){
			map.put("schoolName","");
		}
		try {
			Page<SchoolContacts> page = schoolContactService.querySchoolContactsByPage(map);
			return toResponse(page, ReturnCode.SUCCESS, "分页查询成功!");
		} catch (SQLException e) {
			logger.error(e);
			return toResponse(null, ReturnCode.SUCCESS, "分页查询失败!");
		}
	}

	/**
	 * 导出联系人
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/exportSchoolContacts" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> exportSchoolContacts(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}
		String contentName = request.getParameter("contentName");
		String schoolName = request.getParameter("schoolName");
		if("undefined".equals(contentName)){
			contentName="";
		}
		if("undefined".equals(schoolName)){
			schoolName="";
		}

		try {
//			request.setCharacterEncoding("utf-8");
//			String re = request.getParameter("state");
//			String ad = request.getParameter("ad");
//			String n = request.getParameter("n");
//			String state = new String(re.getBytes("ISO-8859-1"),"UTF-8");
//			String address = new String(ad.getBytes("ISO-8859-1"),"UTF-8");
//			String netname = new String(n.getBytes("ISO-8859-1"),"UTF-8");

			List<SchoolContacts> list = schoolContactService.queryAll(contentName,schoolName);
			List<String> title = new ArrayList<String>();
			title.add("姓名");//这里添加的是你的table里面所有<th></th>里的值
			title.add("学校");
			title.add("职务");
			title.add("办公");
			title.add("手机");
			title.add("邮件");
			title.add("地址");
			title.add("邮编");
			title.add("备注");

			ExcelDownUtil.createExcel(request, response, list, "联系人列表", title);
			return null;
//			return toResponse(page, ReturnCode.SUCCESS, "分页查询成功!");
		} catch (Exception e) {
			logger.error(e);
			return toResponse(null, ReturnCode.SUCCESS, "导出失败!");
		}
	}
	
}
